package com.milotnt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.milotnt.form.MemberQueryForm;
import com.milotnt.mapper.MemberMapper;
import com.milotnt.pojo.MemberEntity;
import com.milotnt.service.MemberService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;

import java.util.Date;
import java.util.List;

@Service
@Slf4j
@Transactional
public class MemberServiceImpl extends ServiceImpl<MemberMapper, MemberEntity> implements MemberService {

    @Autowired
    private MemberMapper memberMapper;

    @Override
    public List<MemberEntity> findAll() {
        return memberMapper.findAll();
    }

    @Override
    public Boolean insertMember(MemberEntity member) {
        Date date = new Date();
        member.setCreateTime(date);
        return memberMapper.insertMember(member);
    }

    @Override
    public Boolean updateMemberByMemberAccount(MemberEntity member, Model model) {
        Boolean account = memberMapper.updateMemberByMemberAccount(member);
        if (!account) {
            return false;
        }
        return account;
    }

    @Override
    public MemberEntity userLogin(MemberEntity member) {
        if (member.getIsDeleted() == 1){
            return null;
        }
        LambdaQueryWrapper<MemberEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(MemberEntity::getMemberAccount, member.getMemberAccount())
                    .eq(MemberEntity::getMemberPassword, member.getMemberPassword());
        return memberMapper.selectOne(queryWrapper);
    }

    @Override
    public Boolean deleteByMemberAccount(Long memberAccount) {
        return memberMapper.deleteByMemberAccount(memberAccount);
    }

    @Override
    public Integer selectTotalCount() {
        return memberMapper.selectTotalCount();
    }

    @Override
    public List<MemberEntity> selectByMemberAccount(MemberQueryForm form) {
        LambdaQueryWrapper<MemberEntity> queryWrapper = new LambdaQueryWrapper<>();

        if (form.getMemberAccount() != null) {
            queryWrapper.eq(MemberEntity::getMemberAccount, form.getMemberAccount());
        }
        if (form.getMemberName() != null && !form.getMemberName().trim().isEmpty()) {
            queryWrapper.like(MemberEntity::getMemberName, form.getMemberName());
        }

        return memberMapper.selectList(queryWrapper);
    }
}
